package org.mzx.shortLink.work.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.RequiredArgsConstructor;
import org.mzx.shortLink.work.domain.entity.TLink;
import org.mzx.shortLink.work.domain.mapper.TLinkMapper;
import org.mzx.shortLink.work.dto.Request.ShortLinkRecycleBinPageReqDTO;
import org.mzx.shortLink.work.dto.Request.recycleBinAddDtoReq;
import org.mzx.shortLink.work.dto.Response.TLinkPageDtoResp;
import org.mzx.shortLink.work.service.recycleBinService;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;

import static org.mzx.shortLink.work.common.enums.RedisData.GOTO_ISNULL_SHORT_LINK_KEY;
import static org.mzx.shortLink.work.common.enums.RedisData.SHORT_LINK_KEY;

@Service
@RequiredArgsConstructor
public class recycleBinServiceImpl extends ServiceImpl<TLinkMapper, TLink>
        implements recycleBinService {


    private final StringRedisTemplate stringRedisTemplate;
    private final TLinkMapper mapper;

    @Override
    @Transactional
    public Void addToBin(recycleBinAddDtoReq requestParam) {
        lambdaUpdate().eq(TLink::getGid,requestParam.getGid())
                .eq(TLink::getFullShortUrl,requestParam.getFullShortUrl())
                .eq(TLink::getEnableStatus,0)
                .set(TLink::getEnableStatus,1)
                .update();
        stringRedisTemplate.delete(SHORT_LINK_KEY+requestParam.getFullShortUrl());
        return null;
    }

    @Override
    public IPage<TLinkPageDtoResp> getByPage(ShortLinkRecycleBinPageReqDTO requestParam) {
        requestParam.setDate(new Date(System.currentTimeMillis()));
        IPage<TLinkPageDtoResp> resultPage = mapper.pageRecycleBinLink(requestParam);
        return resultPage;
    }

    @Override
    @Transactional
    public Void recoverRecycleBin(recycleBinAddDtoReq requestParam) {
        lambdaUpdate().eq(TLink::getGid,requestParam.getGid())
                .eq(TLink::getFullShortUrl,requestParam.getFullShortUrl())
                .eq(TLink::getEnableStatus,1)
                .set(TLink::getEnableStatus,0)
                .update();
        stringRedisTemplate.delete(GOTO_ISNULL_SHORT_LINK_KEY+requestParam.getFullShortUrl());
        return null;
    }

    @Override
    public Void removeRecycleBin(recycleBinAddDtoReq requestParam) {
        lambdaUpdate().eq(TLink::getGid,requestParam.getGid())
                .eq(TLink::getFullShortUrl,requestParam.getFullShortUrl())
                .eq(TLink::getEnableStatus,1)
                .set(TLink::getDelFlag,1)
                .update();
        return null;
    }
}
